package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.mapper.EmpExprMapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.*;
import com.itheima.service.EmpLogService;
import com.itheima.service.EmpService;
import com.itheima.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 员工管理
 */
@Slf4j
@Service
public class EmpServiceImpl implements EmpService {

    @Autowired
    private EmpMapper empMapper;

    @Autowired
    private EmpExprMapper empExprMapper;

    @Autowired
    private EmpLogService empLogService;

    /**
     * 条件分页查询
     *
     * @param empQueryParam
     * @return
     */
    @Override
    public PageResult<Emp>  page(EmpQueryParam empQueryParam) {

        //1.设置PageHelper分页参数
        PageHelper.startPage(empQueryParam.getPage(), empQueryParam.getPageSize());
        //2.执行查询
        Page<Emp> empList = empMapper.list(empQueryParam);
        log.info("查询结果：{}", empList);
        //3. 封装分页结果
        return new PageResult<>(empList.getTotal(), empList.getResult());
    }

    /**
     * 添加员工
     *
     * @param emp
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(Emp emp) {
        try {
            emp.setCreateTime(LocalDateTime.now());
            emp.setUpdateTime(emp.getCreateTime());
            empMapper.insert(emp);

            Integer empId = emp.getId();
            List<EmpExpr> exprList = emp.getExprList();
            if (!CollectionUtils.isEmpty(exprList)) {
                exprList.forEach(empExpr -> empExpr.setEmpId(empId));
                empExprMapper.insertBatch(exprList);
            }
        } finally {
            empLogService.insertLog(new EmpLog(emp.getId(), LocalDateTime.now(), "新增员工"));
        }
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(List<Integer> ids) {
        if (ids != null && !ids.isEmpty()) {
            //1. 根据ID批量删除员工基本信息
            empMapper.deleteBatch(ids);
            //2. 根据员工的ID批量删除员工的工作经历信息
            empExprMapper.deleteBatch(ids);
        }
    }

    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    @Override
    public Emp getById(Integer id) {
        Emp emp = empMapper.selectById(id);
        List<EmpExpr> exprList = empExprMapper.selectByEmpId(id);
        emp.setExprList(exprList);
        return emp;
//        return empMapper.selectById(id);
    }

    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    public Emp getById2(Integer id) {
        return empMapper.selectInfoById(id);
    }

    /**
     * 更新员工信息
     *
     * @param emp
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Emp emp) {
        emp.setUpdateTime(LocalDateTime.now());
        empMapper.update(emp);
        //2. 根据员工ID删除员工的工作经历信息 【删除老的】
        empExprMapper.deleteBatch(Arrays.asList(emp.getId()));
        Integer empId = emp.getId();
        List<EmpExpr> exprList = emp.getExprList();
        if (!CollectionUtils.isEmpty(emp.getExprList())) {
            exprList.forEach(empExpr -> empExpr.setEmpId(empId));
            empExprMapper.insertBatch(exprList);
        }
    }

    @Override
    public LoginInfo login(Emp emp) {
        Emp empInDB = empMapper.getUsernameAndPassword(emp);
        if (empInDB != null) {
            //生成token
            //存储用户信息到令牌里，添加载荷【注意】：非敏感数据
            Map<String, Object> payload = new HashMap<>();
            payload.put("id", empInDB.getId());
            payload.put("username", empInDB.getUsername());
            String token = JwtUtils.generateJwt(payload);
            LoginInfo loginInfo = new LoginInfo(empInDB.getId(), empInDB.getUsername(), empInDB.getName(), token);
            return loginInfo;
        }
        return null;
    }


    @Override
    public List<Emp> findAll() {
        return empMapper.selectAll();
    }
}